﻿using Qy.Core;
using System.Collections.Generic;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace Qy.Scenario;


[AppService]
public class ConfigService : QyRepository<Config>
{
    public ConfigService(ApplicationContext applicationContext) : base(applicationContext)
    {
    }

    /// <summary>
    /// 键名当前列数据
    /// </summary>
    /// <returns></returns>
    public async Task<SytemConfig> GetSytemConfigAsync()
    {
        try
        {
            var dbget = await GetAllListAsync("name asc");
            var options = new JsonSerializerOptions
            {
                NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString,
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                WriteIndented = true
            };
            Config sys1 = dbget.FirstOrDefault(s => s.Name == "SystemInfo");
            SystemInfo systemInfo = JsonSerializer.Deserialize<SystemInfo>(sys1.Data, options);
            Config sys2 = dbget.FirstOrDefault(s => s.Name == "UpLoad");
            UpLoadConfig upLoad = JsonSerializer.Deserialize<UpLoadConfig>(sys2.Data, options);
            Config sys3 = dbget.FirstOrDefault(s => s.Name == "Cache");
            CacheConfig cache = JsonSerializer.Deserialize<CacheConfig>(sys3.Data, options);
            SytemConfig sytemConfig = new()
            {
                SiteName = systemInfo.SiteName,
                UnitOfUse = systemInfo.UnitOfUse,
                SiteUrl = systemInfo.SiteUrl,
                Description = systemInfo.Description,
                Copyright = systemInfo.Copyright,
                Beian = systemInfo.Beian,

                BaseDir = upLoad.BaseDir,
                ImageDir = upLoad.ImageDir,
                ImageSize = upLoad.ImageSize,
                ImageExt = upLoad.ImageExt,
                FileDir = upLoad.FileDir,
                FileExt = upLoad.FileExt,
                FileSize = upLoad.FileSize,

                CmsCache = cache.CmsCache,
                CmsCacheTime = cache.CmsCacheTime,
                ValidCodeOn = cache.ValidCodeOn,
                ValidCodeType = cache.ValidCodeType,
            };
            return sytemConfig;
        }
        catch
        {
            throw;
        }
    }

    /// <summary>
    /// 从缓存中获取上传设置
    /// </summary>
    /// <returns></returns>
    public async Task<UpLoadConfig> GetByUploadAsync()
    {
        SytemConfig sytemConfig = await GetSytemConfigAsync();
        return sytemConfig.AsUpLoadConfig();
    }

    /// <summary>
    /// 从缓存中获取系统设置
    /// </summary>
    /// <returns></returns>
    public async Task<SystemInfo> GetBySystemInfoAsync()
    {
        SytemConfig sytemConfig = await GetSytemConfigAsync();
        return sytemConfig.AsSystemInfo();
    }

    /// <summary>
    /// 从缓存中获取系统设置
    /// </summary>
    /// <returns></returns>
    public async Task<CacheConfig> GetByCacheConfigAsync()
    {
        SytemConfig sytemConfig = await GetSytemConfigAsync();
        return sytemConfig.AsCacheConfig();
    }

    /// <summary>
    /// 根据属性 获取 对应值
    /// </summary>
    /// <returns></returns>
    public async Task<string> GetByFieldNameAsync(string FieldName)
    {
        return ReflexHelper.GetModelValue(FieldName, await GetSytemConfigAsync());
    }

    public async Task<int> UpdateByNameAsync(SytemConfig sytemConfig)
    {
        sytemConfig.Description = StringUtility.StringReplaceNRT(sytemConfig.Description);
        JsonSerializerOptions options = new()
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            WriteIndented = true
        };
        string systemInfo = JsonSerializer.Serialize(sytemConfig.AsSystemInfo(), options);
        string upLoad = JsonSerializer.Serialize(sytemConfig.AsUpLoadConfig(), options);
        string cache = JsonSerializer.Serialize(sytemConfig.AsCacheConfig(), options);

        List<Config> configs = new()
        {
           new Config() { Name = "SystemInfo",Data = systemInfo},
           new Config() { Name = "UpLoad",Data = upLoad},
           new Config() { Name = "Cache",Data = cache},
        };
        int res = await Context.Updateable(configs).WhereColumns(it => new { it.Name }).ExecuteCommandAsync();
        if (res > 0)
        {
            await OnRemoveListAllAsync();
            return res;
        }
        return 0;
    }
}
